<?php
/**
 * Created by PhpStorm.
 * User: wzy12
 * Date: 2018/10/14
 * Time: 14:44
 */

namespace app\admin\model;


use think\Model;
use app\admin\validate\AdPosition as Vali;

class AdPosition extends Model
{
    public function operation($data){
        $query = $this -> where('position_name', $data['position_name']);
        $action = false;
        if(isset($data['id'])){
            $action = true;

            $query -> where('id', '<>', $data['id']);
        }
        // 判断该广告位置是否存在
        $res = $query -> value('id');
        if($res){
            return echoArr(0, '该广告位置已存在');
        }

        // 验证
        $validate = new Vali();
        if(!$validate -> scene('form') -> check($data)){
            return echoArr(0, $validate->getError());
        }

        $result = $this -> allowField(true) -> isUpdate($action) -> save($data);
        if(false === $result){
            return echoArr(0, $this -> getError());
        }else{
            return echoArr(1, '操作成功');
        }
    }

    public function del($data){
        // 验证
        $validate = new Vali();
        if(!$validate -> scene('del') -> check($data)){
            return echoArr(0, $validate->getError());
        }

        $res = model('Ad') -> whereIn('position_id', $data['id']) -> value('id');
        $result = false;
        if(!$res){
            $result = $this -> destroy($data['id']);
        }else{
            return echoArr(0, '请先去除属于此位置的广告');
        }

        if(false === $result){
            return echoArr(0, '操作失败');
        }else{
            return echoArr(1, '操作成功');
        }
    }
}